﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Reflection;

namespace Odelle.WoWArmory.Data
{
    public class CharacterQuery
    {
        public static char QueryDelimiter { get { return Odelle.Utils.Comparisons.FlexibleNumberComparator.Delimiter; } }
        public static char QuerySeparator { get { return'%'; } }

        protected class QueryItem
        {
            public string Name { set; get; }
            public string Value { set; get; }
            public string FilterEntry { get { return this.Name + CharacterQuery.QueryDelimiter.ToString() + this.Value; } }

            public bool Enabled { set; get; }

            public Odelle.Utils.ClassInfoReader.Info Info { set; get; }

            public override string ToString()
            {
                return this.FilterEntry;
            }
        }

        public Odelle.Utils.ClassInfoReader CharaDataInfo { get; private set; }
        public string[] CharaDataItemNames { get; private set; }

        private Dictionary<string,QueryItem> queryEntries;

        private string[] CombinationItems = { "Spec", "Profession" };

        private Odelle.Utils.Comparisons.FlexibleNumberComparator FlexNumCp = new Utils.Comparisons.FlexibleNumberComparator();

        public CharacterQuery()
        {
            this.CharaDataInfo = new Utils.ClassInfoReader(typeof(Odelle.WoWArmory.Data.CharacterData));
            this.CharaDataItemNames = this.CharaDataInfo.GetNames();
            queryEntries = new Dictionary<string, QueryItem>();
        }

        public void Clear()
        {
            queryEntries.Clear();
        }

        public string[] GetNames()
        {
            return                queryEntries.Keys.ToArray<string>();
        }

        public bool Add(string name, string value)
        {
            bool result = this.Add(name);
            if (result)
            {
                this.SetValue(name,value);
            }
            return result;
        }

        public bool Add(string name)
        {
            if (!CharaDataItemNames.Contains<string>(name))
                return false;

            if (queryEntries.Keys.Contains<string>(name))
                return false;

            QueryItem fi = new QueryItem();

            fi.Name = name;
            fi.Value = "*";
            fi.Enabled = true;
            fi.Info = CharaDataInfo.GetInfo(name);

            queryEntries.Add(name, fi);

            return true;
        }

        public bool Remove(string name)
        {
            if (!queryEntries.Keys.Contains<string>(name))
                return false;

            queryEntries.Remove(name);
            return true;
        }

        public bool SetValue(string name, string value)
        {
            if (!queryEntries.Keys.Contains<string>(name))
                return false;

            queryEntries[name].Value = value;
            return true;
        }

        public bool SetEnabled(string name, bool enabled)
        {
            if (!queryEntries.Keys.Contains<string>(name))
                return false;

            queryEntries[name].Enabled = enabled;
            return true;
        }

        public string GetFilterEntries()
        {
            string result = "";

            QueryItem[] values = queryEntries.Values.ToArray<QueryItem>();

            for (int i = 0; i < values.Length; ++i)
            {
                if (values[i].Enabled)
                {
                    if (result != "")
                        result += CharacterQuery.QuerySeparator.ToString();

                    result += values[i].FilterEntry;
                }
            }

            return result;
        }

        public void AddFilterEntries(string filterEntriesText)
        {
            string[] filters = filterEntriesText.Split(CharacterQuery.QuerySeparator);
            for (int i = 0; i < filters.Length; ++i)
            {
                string[] entries = filters[i].Split(CharacterQuery.QueryDelimiter);
                if (entries.Length == 2)
                {
                    Add(entries[0], entries[1]);
                }
            }
        }

        public string[] GetValuesList(string name,CharacterData[] charaDataSet)
        {
            List<string> result = new List<string>();

            bool isContains = queryEntries.Keys.Contains<string>(name);
            bool prev = false;
            if (isContains) // except item if it is in filter list
            {
                prev = queryEntries[name].Enabled;
                queryEntries[name].Enabled = false;
            }

            CharacterData[] maskedDataSet = Query(charaDataSet);

            Type dataType = this.CharaDataInfo.GetInfo(name).DataType;

            if (dataType == typeof(int))
            {
                List<int> val = new List<int>();
                foreach (CharacterData charaData in maskedDataSet)
                {
                    object obj = typeof(CharacterData).GetProperty(name).GetValue(charaData, null);
                    val.Add((int)obj);
                }
                val.Sort();
                for (int i = val.Count - 1; i >= 0; --i)
                {
                    if (!result.Contains(val[i].ToString()))
                        result.Add(val[i].ToString());
                }
            }
            else if (dataType == typeof(long))
            {
                List<long> val = new List<long>();
                foreach (CharacterData charaData in maskedDataSet)
                {
                    object obj = typeof(CharacterData).GetProperty(name).GetValue(charaData, null);
                    val.Add((long)obj);
                }
                val.Sort();
                for (int i = val.Count - 1; i >= 0; --i)
                {
                    if (!result.Contains(val[i].ToString()))
                        result.Add(val[i].ToString());
                }
            }
            else if (dataType == typeof(double))
            {
                List<double> val = new List<double>();
                foreach (CharacterData charaData in maskedDataSet)
                {
                    object obj = typeof(CharacterData).GetProperty(name).GetValue(charaData, null);
                    val.Add((double)obj);
                }
                val.Sort();
                for (int i = val.Count - 1; i >= 0; --i)
                {
                    if (!result.Contains(val[i].ToString()))
                        result.Add(val[i].ToString());
                }
            }
            else if (dataType == typeof(float))
            {
                List<float> val = new List<float>();
                foreach (CharacterData charaData in maskedDataSet)
                {
                    object obj = typeof(CharacterData).GetProperty(name).GetValue(charaData, null);
                    val.Add((float)obj);
                }
                val.Sort();
                for (int i = val.Count - 1; i >= 0; --i)
                {
                    if (!result.Contains(val[i].ToString()))
                        result.Add(val[i].ToString());
                }
            }
            else if (dataType == typeof(string))
            {
                foreach (CharacterData charaData in maskedDataSet)
                {
                    object obj = typeof(CharacterData).GetProperty(name).GetValue(charaData, null);

                    if (CombinationItems.Contains(name))
                    {
                        string[] vals = ((string)obj).Split('/');

                        for (int v = 0; v < vals.Length; ++v)
                        {
                            if (!result.Contains(vals[v]))
                                result.Add(vals[v]);
                        }
                    }
                    else
                    {
                        if (!result.Contains((string)obj))
                            result.Add((string)obj);
                    }
                }
                result.Sort();
            }
            else if (dataType == typeof(DateTime))
            {
                List<DateTime> val = new List<DateTime>();
                foreach (CharacterData charaData in maskedDataSet)
                {
                    object obj = typeof(CharacterData).GetProperty(name).GetValue(charaData, null);
                    val.Add((DateTime)obj);
                }
                val.Sort();
                for (int i = val.Count - 1; i >= 0; --i)
                {
                    if (!result.Contains(val[i].Date.ToShortDateString()))
                    {
                        result.Add(val[i].Date.ToShortDateString());
                    }
                }
            }

            if (isContains)
            {
                queryEntries[name].Enabled = true;
            }

            return result.ToArray();
        }

        public CharacterData[] Query(CharacterData[] charaDataSet)
        {
            List<CharacterData> result = new List<CharacterData>();

            for (int i = 0; i < charaDataSet.Length; ++i)
            {
                if (IsMatch(charaDataSet[i]))
                    result.Add(charaDataSet[i]);
            }

            return result.ToArray();
        }

        public bool IsMatch(CharacterData charaData)
        {
            bool result = true;

            foreach (QueryItem q in queryEntries.Values)
            {
                if (q.Enabled)
                {
                    result = IsMatchQueryItem(charaData, q);
                    if (result == false)
                        break;
                }
            }

            return result;
        }

        private bool IsMatchQueryItem(CharacterData charaData, QueryItem query)
        {
            if (query.Value == "*")
                return true;

            if (query.Enabled == false)
                return true;

            if (charaData == null)
                return false;

            object obj = typeof(CharacterData).GetProperty(query.Name).GetValue(charaData, null);

            bool result = false;
            if (query.Info.DataType == typeof(int))
            {
                result = FlexNumCp.Compare((int)obj,query.Value);
            }
            else if (query.Info.DataType == typeof(long))
            {
                result = FlexNumCp.Compare((long)obj, query.Value);
            }
            else if (query.Info.DataType == typeof(double))
            {
                result = FlexNumCp.Compare((double)obj, query.Value);
            }
            else if (query.Info.DataType == typeof(float))
            {
                result = FlexNumCp.Compare((float)obj, query.Value);
            }
            else if (query.Info.DataType == typeof(string))
            {
                if (CombinationItems.Contains(query.Name))
                {
                    string[] vals = ((string)obj).Split('/');

                    result = (vals.Contains( query.Value));
                }
                else
                {
                    result = ((string)obj == query.Value);
                }
            }
            else if (query.Info.DataType == typeof(DateTime))
            {
                result = FlexNumCp.Compare((DateTime)obj, query.Value);
            }

            return result;
        }
    }
}
